//
//  PlayingViewController.m
//  BabyBedtimeStory
//
//  Created by qianfeng on 15-6-26.
//  Copyright (c) 2015年 张鹏毅. All rights reserved.
//

#import "PlayingViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "DetailViewController.h"
#import "HistoricalCell.h"
#import "MyViewController.h"

#import "DownloadViewController.h"

#define kScreenSize [UIScreen mainScreen].bounds.size

@interface PlayingViewController ()<UITableViewDelegate,UITableViewDataSource,AVAudioPlayerDelegate>
{
    AFHTTPRequestOperationManager *_manager;
}
@property (nonatomic,strong) UISlider *slider;
@property (nonatomic,strong) AVPlayerItem *item;
@property (nonatomic,strong) UIButton *button;
@property (nonatomic,strong) UILabel *titlelabel;
@property (nonatomic,strong) UILabel *TimeLabel1;
@property (nonatomic,strong) UILabel *TimeLabel2;
@property (nonatomic) BOOL isPlaying;
@property (nonatomic) BOOL isStop;
@property (nonatomic,strong) StoryModel *Pmodel;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic) BOOL isPaste;

@property (nonatomic) NSInteger i;
@property (nonatomic) NSInteger lastI;
@property (nonatomic,strong) NSMutableArray *dataArr1;
@property (nonatomic) BOOL isToo;
@end

@implementation PlayingViewController

+(AVPlayer *)sharedSingleton{
    @synchronized (self){
        if (!player) {
            player = nil;
            player = [[self alloc] init];
        }
    }
    return player;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.isPlaying = NO;
    self.isStop = NO;
    self.isPaste = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatLeftItem];
    [self creatAf];
    [self StartDownloadingData];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(defaultClick:) name:kFabcdefge object:nil];
    
}

-(void)defaultClick:(NSNotification *)tyf{
    [player pause];
    player = nil;
}

#pragma mark - 创建播放
-(void)creatPlayer:(StoryModel *)model{
    self.Pmodel = model;
    AVURLAsset *assect = [[AVURLAsset alloc]initWithURL:[NSURL URLWithString:model.audio_64_url ] options:nil];
    self.item = [[AVPlayerItem alloc]initWithAsset:assect automaticallyLoadedAssetKeys:nil];
    player = [AVPlayer playerWithPlayerItem:self.item];
    [self.item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self justPlay];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:1];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIButton *button = (UIButton *)[self.view viewWithTag:102];
            [button setImage:[[UIImage imageNamed:@"ic_suspended"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            self.isRefreshing = YES;
        });
    });
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        if (self.item.status == AVPlayerItemStatusReadyToPlay) {
            [player play];
            __weak typeof (self) weakSelf = self;
            [player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                CMTime totalTime = player.currentItem.duration;
                CGFloat currentTimeSeconds = CMTimeGetSeconds(time);
                CGFloat totalSeconds = CMTimeGetSeconds(totalTime);
                weakSelf.slider.value = currentTimeSeconds/totalSeconds*1.0;
                
                
                weakSelf.TimeLabel1.text = [NSString stringWithFormat:@"%@",[self TimeChange:(int)currentTimeSeconds]];
                if (weakSelf.slider.value > 0.999) {
                    UIButton *btn = (UIButton *)[self.view viewWithTag:102];
                    [btn setImage:[[UIImage imageNamed:@"ic_start"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
                    self.isPlaying = NO;
                    weakSelf.slider.value = 0;
                    weakSelf.isStop = YES;
                }
                
                
            }];
        }else{
            NSLog(@"无法播放");
        }
        
    }
}

#pragma mark - 定制返回按钮
-(void)creatLeftItem{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button setImage:[[UIImage imageNamed:@"ic_nac_back_down"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = 501;
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = item;
}

#pragma mark - 创建下载数据
-(void)creatAf{
    _manager = [AFHTTPRequestOperationManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
}

-(void)StartDownloadingData{
    __weak typeof(self) weakSelf =self;
    NSString *url = [NSString stringWithFormat:playUrl,self.model.id];
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *arrDict = dict[@"data"];
            NSDictionary *albumDict =arrDict[@"album"];
            StoryModel *model = [[StoryModel alloc]init];
            [model setValuesForKeysWithDictionary:albumDict];
            [weakSelf creatUpView:model];
            
            NSDictionary *contentDict = arrDict[@"content"];
            StoryModel *modelC = [[StoryModel alloc]init];
            [modelC setValuesForKeysWithDictionary:contentDict];
            [weakSelf creatDown:modelC];
            [weakSelf creatPlayer:modelC];
            
            StoryModel *modelAll = [[StoryModel alloc]init];
            modelAll.title = modelC.title;
            modelAll.id = modelC.id;
            modelAll.album_title = model.title;
            modelAll.image_url = model.image_url;
            [[DBManager sharedManager]insertModel:modelAll recordType:kFavorite];
            self.modelA = modelAll;
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark - 头视图
-(void)creatUpView:(StoryModel *)model{
    self.ChangID = model.id;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, kScreenSize.height/2-64)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.image_url] placeholderImage:[UIImage imageNamed:@"yujiazai"]];
    [self.view addSubview:imageView];
}

#pragma mark - 界面布局
-(void)creatDown:(StoryModel *)model{
    self.titlelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, kScreenSize.height/2, kScreenSize.width, 22)];
    self.titlelabel.text = [NSString stringWithFormat:@" %@",model.title];
    self.titlelabel.textAlignment = NSTextAlignmentCenter;
    self.titlelabel.font = [UIFont fontWithName:@"Didot" size:15];
    [self.view addSubview:self.titlelabel];
    NSArray *title = @[@"ic_on_a",@"ic_start",@"ic_next"];
    for (NSInteger i = 0; i < title.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 101+i;
        button.frame = CGRectMake(i*kScreenSize.width/3, kScreenSize.height/2+22, kScreenSize.width/3, kScreenSize.height/8-10);
        [button setImage:[[UIImage imageNamed:title[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
    
    _slider = [[UISlider alloc]initWithFrame:CGRectMake(10, kScreenSize.height/2+kScreenSize.height/8+12, kScreenSize.width-20, kScreenSize.height/8-20)];
    _slider.maximumValue = 1.0;
    _slider.minimumValue = 0.0;
    [_slider addTarget:self action:@selector(sliderClick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_slider];
    
    self.TimeLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(10, kScreenSize.height*3/4-8, 60, 20)];
    self.TimeLabel1.font = [UIFont fontWithName:@"Didot" size:14];
    self.TimeLabel1.text = @"00:00:00";
    [self.view addSubview:self.TimeLabel1];
    
    self.TimeLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(kScreenSize.width-60, kScreenSize.height*3/4-8, 60, 20)];
    self.TimeLabel2.font = [UIFont fontWithName:@"Didot" size:14];
    self.TimeLabel2.text = model.duration;
    [self.view addSubview:self.TimeLabel2];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, kScreenSize.height*3/4+12, kScreenSize.width, kScreenSize.height/4-49-10)];
    label.userInteractionEnabled = YES;
    NSArray *titleName = @[@"ic_download",@"Sh"];
    for (NSInteger i = 0; i < titleName.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 201+i;
        button.frame = CGRectMake(20+i*(kScreenSize.width-90), 20, 35, 35);
        [button setImage:[[UIImage imageNamed:titleName[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [label addSubview:button];
    }
    [self.view addSubview:label];
    
    UILabel *Dlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, kScreenSize.height*7/8+2, kScreenSize.width, 49)];
    Dlabel.userInteractionEnabled = YES;
    NSArray *titleArr = @[@"ic_player_list",@"ic_player_history"];
    for (NSInteger i = 0; i < titleArr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 301+i;
        button.frame = CGRectMake(20+i*(kScreenSize.width-80), 15, 40, 30);
        [button setImage:[[UIImage imageNamed:titleArr[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [Dlabel addSubview:button];
    }
    [self.view addSubview:Dlabel];
}

#pragma mark - slider方法
-(void)sliderClick:(UISlider *)slider{
    float progressValue = slider.value;
    CMTime totalTime = player.currentItem.duration;
    [player seekToTime:CMTimeMultiplyByFloat64(totalTime, progressValue)];
}

-(void)btnClick:(UIButton *)btn{
    switch (btn.tag) {
        case 101://上一首
        {
                PlayingViewController *vc = [[PlayingViewController alloc]init];
                if (self.SelectNum-1<0) {
                    vc.SelectNum = self.count-1;
                    vc.count = self.count;
                }else{
                    vc.count = self.count;
                    vc.SelectNum = self.SelectNum -1;
                }
//            vc.isYes = self.isYes;
                vc.dataArr = self.dataArr;
                vc.model = self.dataArr[vc.SelectNum];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        case 102://播放
        {
            
            
            if (self.isPlaying) {
                [btn setImage:[[UIImage imageNamed:@"ic_suspended"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
                if (self.isStop) {
                    [self.item removeObserver:self forKeyPath:@"status"context:nil];
                    StoryModel *model = self.Pmodel;
                    [self creatPlayer:model];
                    self.isStop = NO;
                }
                [self justPlay];
                self.isPlaying = NO;
            }else{
                [btn setImage:[[UIImage imageNamed:@"ic_start"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
                [player pause];
                self.isPlaying = YES;
            }
            
        }
            break;
        case 103://下一首
        {
                PlayingViewController *vc = [[PlayingViewController alloc]init];
                if (self.SelectNum+2 > self.count) {
                    vc.SelectNum = 0;
                    vc.count = self.count;
                }else{
                    vc.count = self.count;
                    vc.SelectNum = self.SelectNum +1;
                }
//            vc.isYes = self.isYes;
                vc.dataArr = self.dataArr;
                vc.model = self.dataArr[vc.SelectNum];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
            
        case 201://定时
        {
            __weak typeof(self)weakSelf = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"开始下载");
                DownloadViewController *dvc = [[DownloadViewController alloc]init];
                [dvc startDataWithUrl:weakSelf.model];
            });
        }
            break;
        case 202://下载
        {
            [[DBManager sharedManager]insertModel:self.modelA recordType:kDownloads];
            BOOL isYes = [[DBManager sharedManager]isExistAppForAppId:self.modelA.id
                                                           recordType:kDownloads];
            if (isYes) {
                [self creatAlter:@"收藏成功"];
            }else{
                [self creatAlter:@"收藏失败"];
            }
            
        }
            break;
        case 301://列表
        {
            self.lastI = self.i;
            self.i = 0;
            [self HistoricalAndPlay];
        }
            break;
        case 302://历史
        {
            self.lastI = self.i;
            self.i= 1;
            [self HistoricalAndPlay];
        }
            break;
        case 501:
        {
            DetailViewController *deta = [[DetailViewController alloc]init];
            deta.id = self.ChangID;
//            if (!self.isYes) {
//                deta.SelectNum = self.SelectNum;
////                deta.isBool = 1;
//            }
            [self.navigationController pushViewController:deta animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    MyViewController *vc = [[MyViewController alloc]init];
    [vc isRingWithDataArr:^(NSMutableArray *dataArr) {
        self.dataArr1 = dataArr;
        [self.tableView reloadData];
        NSLog(@"1");
    }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.item removeObserver:self forKeyPath:@"status"];
    self.tabBarController.tabBar.hidden = NO;
    self.tableView.alpha = 0;
}

#pragma mark - 时间转换
-(NSString *)TimeChange:(int)time{
    int h = 0;
    int m = 0;
    int s = 0;
    if (time/60>=1) {
        if (time/3600>=1) {
            h = time%3600;
            time = time - 3600*h;
        }
        m = time/60;
        time = time - 60*m;
    }
    s = time;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",h,m,s];
}

#pragma mark - 列表
-(void)creatView{
    if (self.i == 0) {
        if (self.tableView) {
            self.tableView.frame = CGRectMake(10, kScreenSize.height/2-50, kScreenSize.width/2, kScreenSize.height/2);
        }else{
            self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(10, kScreenSize.height/2-50, kScreenSize.width/2, kScreenSize.height/2)];
        }
        
    }else if(self.i == 1){
        if (self.tableView) {
            self.tableView.frame = CGRectMake(kScreenSize.width/2-10, kScreenSize.height/2-50, kScreenSize.width/2, kScreenSize.height/2);
        }else{
            self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(kScreenSize.width/2-10, kScreenSize.height/2-50, kScreenSize.width/2, kScreenSize.height/2)];
        }
    }
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.layer.masksToBounds = YES;
    self.tableView.layer.cornerRadius = 8;
    [self.tableView registerNib:[UINib nibWithNibName:@"HistoricalCell" bundle:nil] forCellReuseIdentifier:@"HistoricalCell"];
    [[[[UIApplication sharedApplication]keyWindow]rootViewController].view addSubview:self.tableView];
    [self.tableView reloadData];
    self.tableView.alpha = 0;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.i == 0) {
        return self.dataArr.count;
    }else{
        NSArray *arr = [[DBManager sharedManager]readModelsWithRecordType:kFavorite];
        self.dataArr1 = [NSMutableArray arrayWithArray:arr];
        return self.dataArr1.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HistoricalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HistoricalCell" forIndexPath:indexPath];
    if (self.i == 0) {
        StoryModel *model = self.dataArr[indexPath.row];
        [cell showWithModel:model];
    }else{
        StoryModel *model = self.dataArr1[indexPath.row];
        [cell showWithModel:model];
    }
    return cell;
}

#pragma mark - 选中cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.tableView.alpha = 0;
    if (self.i == 0) {
        PlayingViewController *vc = [[PlayingViewController alloc]init];
//        vc.SelectNum = indexPath.row;
        vc.count = self.dataArr.count;
        vc.dataArr = self.dataArr;
        vc.model = self.dataArr[indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        PlayingViewController *his = [[PlayingViewController alloc]init];
        his.count = self.dataArr1.count;
//        his.SelectNum = indexPath.row;
        his.dataArr = self.dataArr1;
//        his.isYes = YES;
        his.model = self.dataArr1[indexPath.row];
        [self.navigationController pushViewController:his animated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 30;
    }
    return 0;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        if (self.i == 0) {
            return [NSString stringWithFormat:@"播放列表"];
        }else{
            return [NSString stringWithFormat:@"播放历史"];
        }
    }
    return nil;
}

#pragma mark - 历史和播放判断
-(void)HistoricalAndPlay{
    [self creatView];
    if (self.isPaste) {
        self.isPaste = !self.isPaste;
        self.tableView.alpha = 0;
    }else{
        self.isPaste = !self.isPaste;
        self.tableView.alpha = 1;
    }
    if ((self.lastI+self.i)%2 == 1) {
        self.isPaste = !self.isPaste;
        self.tableView.alpha = 1;
        self.isToo = YES;
    }else if((self.lastI+self.i)%2 == 0&&self.isToo) {
        self.isPaste = !self.isPaste;
        self.tableView.alpha = 0;
        self.isToo = NO;
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.tableView.alpha = 0;
}

-(void)justPlay{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [player play];
}

@end
